package lancoo.com.net.retrofitrxjava;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Author: pengmi;
 * Time: 2017/6/5;
 * Description: 网络拦截（主要是统一添加头部）
 */
public class UrlInterceptor implements Interceptor {
    private static Map<String,String> foreverMap=new HashMap<>();
    private static Map<String,String> tempMap=new HashMap<>();
    private static boolean isAddTempHead=false;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if(!isAddTempHead){
            tempMap.clear();
        }
        isAddTempHead=false;
        Iterator entries=foreverMap.entrySet().iterator();
        while (entries.hasNext()){
            Map.Entry entry = (Map.Entry) entries.next();
            request = request.newBuilder().addHeader((String)entry.getKey(),
                    (String)entry.getValue()).build();
        }
        Iterator tempEntries=tempMap.entrySet().iterator();
        while (tempEntries.hasNext()){
            Map.Entry entry = (Map.Entry) tempEntries.next();
            request = request.newBuilder().addHeader((String)entry.getKey(),
                    (String)entry.getValue()).build();
        }

        return chain.proceed(request);
    }
    public static void setAllHeadMessage(Map<String,String> map){
        foreverMap.clear();
        foreverMap.putAll(map);
    }
    public static void setSingleHeadMessage(Map<String,String> map){
        isAddTempHead=true;
        tempMap.clear();
        tempMap.putAll(map);
    }
}
